﻿using Microsoft.AspNetCore.SignalR;

namespace LanqiQAwebapi.ConnectHubs
{

  
    public class ConnectHub:Hub
    {
        private static readonly Dictionary<string, string> _userConnections = new();

     

        // 用户连接时调用
        public override async Task OnConnectedAsync()
        {
            Console.WriteLine($"Client connected: {Context.ConnectionId}");

            // 如果是默认用户，自动注册
            var user = Context.GetHttpContext()?.Request.Query["user"].ToString();
            if (!string.IsNullOrEmpty(user) )
            {
                _userConnections[user] = Context.ConnectionId;
                await Clients.All.SendAsync("UserOnline", user);
            }

            await base.OnConnectedAsync();
        }

        // 用户断开连接时调用
        public override async Task OnDisconnectedAsync(Exception? exception)
        {
            // 从连接字典中移除用户
            var userEntry = _userConnections.FirstOrDefault(x => x.Value == Context.ConnectionId);
            if (userEntry.Key != null)
            {
                _userConnections.Remove(userEntry.Key);
        
                    await Clients.All.SendAsync("UserOffline", userEntry.Key);
               
            }

            Console.WriteLine($"Client disconnected: {Context.ConnectionId}");
            await base.OnDisconnectedAsync(exception);
        }

        // 用户注册连接
        public async Task RegisterUser(string username)
        {
            _userConnections[username] = Context.ConnectionId;
            await Clients.All.SendAsync("UserOnline", username);
            await Clients.Caller.SendAsync("RegistrationSuccess", $"User {username} registered successfully");
        }

        // 一对一聊天
        public async Task SendMessage(string targetUser, string message)
        {
            var sender = _userConnections.FirstOrDefault(x => x.Value == Context.ConnectionId).Key;

            if (string.IsNullOrEmpty(sender))
            {
                await Clients.Caller.SendAsync("Error", "Please register first");
                return;
            }

            // 检查目标用户是否在线（包括默认在线用户）
            bool isTargetOnline = _userConnections.ContainsKey(targetUser);

            if (isTargetOnline)
            {
                if (_userConnections.TryGetValue(targetUser, out var targetConnectionId))
                {
                    // 发送给在线的目标用户
                    await Clients.Client(targetConnectionId).SendAsync("ReceiveMessage", sender, message);
                }
                // 如果是默认在线用户，消息会被存储，等用户真正连接时接收

                // 同时发送给自己（确认消息已发送）
                await Clients.Caller.SendAsync("ReceiveMessage", sender, message);

                Console.WriteLine($"Message from {sender} to {targetUser}: {message}");
            }
            else
            {
                // 目标用户不在线
                await Clients.Caller.SendAsync("Error", $"User {targetUser} is offline");
            }
        }

        // 获取在线用户列表（包括默认在线用户）
        public async Task GetOnlineUsers()
        {
            var allOnlineUsers = _userConnections.Keys
               
                .Distinct()
                .ToList();
            await Clients.Caller.SendAsync("OnlineUsers", allOnlineUsers);
        }

        // 其他方法保持不变...
        public async Task JoinAuthorGroup(string authorId)
        {
            await Groups.AddToGroupAsync(Context.ConnectionId, $"author_{authorId}");
            await Clients.Caller.SendAsync("GroupJoined", $"Joined author group: {authorId}");
        }

        public async Task SendToAuthorGroup(string authorId, string message)
        {
            var sender = _userConnections.FirstOrDefault(x => x.Value == Context.ConnectionId).Key;
            await Clients.Group($"author_{authorId}").SendAsync("AuthorGroupMessage", sender, message);
        }

        public async Task JoinEssayCommentGroup(string essayCommentId)
        {
            await Groups.AddToGroupAsync(Context.ConnectionId, $"essay_{essayCommentId}");
            await Clients.Caller.SendAsync("GroupJoined", $"Joined essay comment group: {essayCommentId}");
        }

        public async Task SendToEssayCommentGroup(string essayCommentId, string message)
        {
            var sender = _userConnections.FirstOrDefault(x => x.Value == Context.ConnectionId).Key;
            await Clients.Group($"essay_{essayCommentId}").SendAsync("EssayCommentMessage", sender, message);
        }
    }
}
